package user

import (
	"cms/model"
	service "cms/serivce"
	"engine/cache"
	"engine/dto"
	emodel "engine/model"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"lib/db"
	"lib/response"
	sferrors "lib/sf-errors"
	"strconv"
	"strings"
	"time"
	"unicode"
)

type ProductHandel struct{}

// /api/user/v2/products pay
func (pro *ProductHandel) CreateOrderHandel(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	//if operator.Level < 40 {
	//	response.Error(ctx, sferrors.NewStringf("暂时只支持当前级别为40级别以上"))
	//	return
	//}

	var req model.MyProOrderCreateReq
	if err = ctx.ShouldBind(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.ErrorBadRequest))
		return
	}
	if req.Num != 1 {
		response.Error(ctx, sferrors.NewStringf("一次只能1个"))
		return
	}

	var address emodel.My_user_address
	if err = db.GetDb().Where("id=? and user_id=?", req.Aid, operator.Id).First(&address).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	var product emodel.My_shop
	if err = db.GetDb().Where("id=?", req.Pid).First(&product).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	stock, _ := strconv.Atoi(product.Stock)
	if stock < 1 {
		response.Error(ctx, sferrors.NewStringf("库存不足"))
		return
	}
	if product.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}
	amount := product.Money * float64(req.Num)
	point := product.Point * float64(req.Num)

	orderSn := fmt.Sprintf("%d%d", time.Now().UnixMicro(), operator.Id)
	nowTime := time.Now()
	newProOrder := emodel.My_proorder{
		Aid:        req.Aid,
		Type:       "0",
		Pid:        product.Id,
		Uid:        operator.Id,
		Mobile:     operator.Mobile,
		Title:      product.Title,
		Desc:       product.Desc,
		Num:        req.Num,
		Price:      product.Money,
		Amount:     amount,
		OrderSn:    orderSn,
		Province:   address.Province,
		City:       address.City,
		Area:       address.Area,
		Images:     product.Images,
		Address:    address.Address,
		Tel:        address.Tel,
		Name:       address.Name,
		AddressAll: address.Province + " " + address.City + " " + address.Area + " " + address.Address,
		CreateTime: &nowTime,
	}

	//ss, err := service.CreateAppPayment(orderSn, product.Desc, "1")
	//
	//if err != nil {
	//	response.Error(ctx, err)
	//	return
	//}
	//response.OkData(ctx, ss)
	//
	//return

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		if myUser.Money < amount {
			return sferrors.NewStringf("通用积分不足")
		}

		if myUser.Point < point {
			return sferrors.NewStringf("贡献积分不足")
		}

		txErr = service.CreateUserLog(tx, myUser, amount, 31, myUser.Id, "购买商品")
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateUserPointLog(tx, myUser, point, 38, myUser.Id, "购买商品")
		if txErr != nil {
			return txErr
		}

		//txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pUser, pUser.Id).Error
		//if txErr != nil {
		//	return txErr
		//}
		//txErr = service.CreateUserLog(tx, &pUser.My_user, giftMoney.Num, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠")
		//if txErr != nil {
		//	return txErr
		//}
		//if txErr = service.CreateUserPointLog(tx, &pUser.My_user, giftMoney.Num*100, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠"); txErr != nil {
		//	return txErr
		//}
		if err = tx.Create(&newProOrder).Error; err != nil {
			response.Error(ctx, err)
			return err
		}
		tx.Exec("update my_shop set stock=stock-1 where id=? ", product.Id)

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[string](ctx, "操作成功")

}

func (pro *ProductHandel) CreateOrderPointHandel(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var req model.MyProOrderCreateReq
	if err = ctx.ShouldBind(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.ErrorBadRequest))
		return
	}
	if req.Num < 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}

	var address emodel.My_user_address
	if err = db.GetDb().Where("id=? and user_id=?", req.Aid, operator.Id).First(&address).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	var product emodel.My_shop
	if err = db.GetDb().Where("id=?", req.Pid).First(&product).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	if product.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}

	amount := product.Money * float64(req.Num)

	orderSn := fmt.Sprintf("%d%d", time.Now().UnixMicro(), operator.Id)
	nowTime := time.Now()
	newProOrder := emodel.My_proorder{
		Aid:        req.Aid,
		Type:       "0",
		Pid:        product.Id,
		Uid:        operator.Id,
		Mobile:     operator.Mobile,
		Title:      product.Title,
		Desc:       product.Desc,
		Num:        req.Num,
		Price:      product.Money,
		Amount:     amount,
		Status:     1,
		ZfTime:     &nowTime,
		OrderSn:    orderSn,
		Province:   address.Province,
		City:       address.City,
		Area:       address.Area,
		Images:     product.Images,
		Address:    address.Address,
		Tel:        address.Tel,
		Name:       address.Name,
		AddressAll: address.Province + " " + address.City + " " + address.Area + " " + address.Address,
		CreateTime: &nowTime,
	}
	//煎炒钱

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		if err = tx.Create(&newProOrder).Error; err != nil {
			return err
		}

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		if myUser.Money < amount {
			return sferrors.NewStringf("积分不足")
		}
		txErr = service.CreateUserLog(tx, myUser, amount, 31, myUser.Id, "购买商品")
		if txErr != nil {
			return txErr
		}

		//txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pUser, pUser.Id).Error
		//if txErr != nil {
		//	return txErr
		//}
		//txErr = service.CreateUserLog(tx, &pUser.My_user, giftMoney.Num, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠")
		//if txErr != nil {
		//	return txErr
		//}
		//if txErr = service.CreateUserPointLog(tx, &pUser.My_user, giftMoney.Num*100, 1, myUser.Id, "收到 "+fmt.Sprintf("%d", myUser.Id)+" 的转赠"); txErr != nil {
		//	return txErr
		//}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[string](ctx, "操作成功")

}

// GetProOrderHandel  我的订单
// @Summary		我的订单
// @Description	我的订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-order/{TYPE}/{PAGE} [GET]
func (pro *ProductHandel) GetProOrderHandel(ctx *gin.Context) {
	//
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")

	if pageInt == 0 {
		pageInt = 1
	}
	query := db.GetDb()
	query = query.Where("status>0 and uid=? ", operator.Id).Order("id desc")
	if types != "0" {
		query = query.Where("status=?", types)
	}
	list, err := dto.Paginate[emodel.My_proorder](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 8,
		ShowSQL:  true,
	})

	response.OkData(ctx, list)
}

// GetProOrderDetailHandel  订单详情
// @Summary		订单详情
// @Description	订单详情
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-order/{id} [GET]
func (pro *ProductHandel) GetProOrderDetailHandel(ctx *gin.Context) {
	//
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, err)
		return
	}

	var data emodel.My_proorder
	if err := db.GetDb().Where("uid=? and id=?", operator.Id, id).First(&data).Error; err != nil {
		response.Error(ctx, err)
	}

	response.OkData(ctx, data)
}

// GetProOrderDetailAddressHandel  快递信息详情
// @Summary		快递信息详情
// @Description	快递信息详情
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-order-address/{id} [GET]
func (pro *ProductHandel) GetProOrderDetailAddressHandel(ctx *gin.Context) {
	//
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, err)
		return
	}

	var data emodel.My_proorder
	if err := db.GetDb().Where("uid=? and id=?", operator.Id, id).First(&data).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	var address emodel.My_order_address
	if err := db.GetDb().Where("oid=?", id).First(&address).Error; err != nil {
		//response.Error(ctx, err)
		//return
	}
	type repspData struct {
		ProOrder emodel.My_proorder      `json:"proOrder"`
		Address  emodel.My_order_address `json:"address"`
	}
	/*
		ACCEPT  已揽收
		TRANSPORT  运输中
		SIGN 已签收
	*/

	resp := repspData{
		ProOrder: data,
		Address:  address,
	}
	response.OkData(ctx, resp)
}
func IsDigitsOnly(s string) bool {
	for _, c := range s {
		if !unicode.IsDigit(c) {
			return false
		}
	}
	return len(s) > 0 // 如果字符串为空，返回false
}

// CreateOnlineOrder  添加订单
// @Summary		添加订单
// @Description	添加订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-online-order/{orderSn} [GET]
func (pro *ProductHandel) CreateOnlineOrder(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	orderNo := strings.TrimSpace(ctx.Param("orderSn"))
	if orderNo == "" {
		response.Error(ctx, sferrors.NewStringf("单号错误！"))
		return
	}
	orderSn := ctx.Param("orderSn") // 假设这是你的参数
	if !IsDigitsOnly(orderSn) {
		response.Error(ctx, sferrors.NewStringf("单号错误!!"))
		return
	}
	if len(orderNo) != 19 {
		response.Error(ctx, sferrors.NewStringf("单号错误!!!"))
		return
	}

	orderType := 0
	req := model.QueryUserLogRequest{}
	if err := ctx.BindQuery(&req); err != nil {
		req.OrderType = 0
	}
	orderType = req.OrderType
	if orderType == 0 {
		childUserCount := dto.GetChildSysUserCountById(operator.Id, 1)
		if childUserCount < 9 {
			response.Error(ctx, sferrors.NewStringf("最少要有9个有效直推"))
			return
		}
	}

	var newOrder emodel.My_online_order_levels
	db.GetDb().Where("order_no=?", orderNo).First(&newOrder)
	if newOrder.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("该订单已在阶梯订单中提交过"))
		return
	}

	//my-online-order
	var data emodel.My_online_order
	db.GetDb().Where("order_no=? and status<2", orderNo).First(&data)

	if data.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("单号已存在！"))
		return
	}
	t := time.Now()

	newData := emodel.My_online_order{
		OrderNo:    orderNo,
		Uid:        operator.Id,
		Mobile:     operator.Mobile,
		CreateTime: &t,
	}
	if orderType == 2 {
		//查询我的上级
		puser, err := dto.GetSysUserDetailById(operator.Pid)
		if err != nil {
			response.Error(ctx, err)
			return
		}
		newData.Uid = puser.Id
		newData.Mobile = puser.Mobile
		newData.ChId = operator.Id
	}

	if err = db.GetDb().Create(&newData).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "Success")
}

// CreateOnlineOrderTow  添加订单
// @Summary		添加订单
// @Description	添加订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-online-order/{orderSn}/{orderType} [POST]
func (pro *ProductHandel) CreateOnlineOrderTow(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	orderNo := strings.TrimSpace(ctx.Param("orderSn"))
	if orderNo == "" {
		response.Error(ctx, sferrors.NewStringf("单号错误！"))
		return
	}

	if len(orderNo) != 19 {
		response.Error(ctx, sferrors.NewStringf("单号错误!!!"))
		return
	}

	orderType := strings.TrimSpace(ctx.Param("orderType"))
	if orderType == "" {
		orderType = "0"
	}

	if orderType == "0" {
		childUserCount := dto.GetChildSysUserCountById(operator.Id, 1)
		if childUserCount < 9 {
			response.Error(ctx, sferrors.NewStringf("最少要有9个有效直推"))
			return
		}
	}

	var newOrder emodel.My_online_order_levels
	db.GetDb().Where("order_no=?", orderNo).First(&newOrder)
	if newOrder.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("该订单已在阶梯订单中提交过"))
		return
	}

	var dataW emodel.My_order_w
	db.GetDb().Where("order_no=? ", orderNo).First(&dataW)
	if dataW.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("该订单已被解锁使用！"))
		return
	}

	//my-online-order
	var data emodel.My_online_order
	db.GetDb().Where("order_no=? and status<2", orderNo).First(&data)
	if data.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("单号已存在！"))
		return
	}

	skuids, respone, err := service.GetYongjinOrderDetail(orderNo)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if respone != true {
		response.Error(ctx, sferrors.NewStringf("请确定订单已经全部取消或退款"))
		return
	}

	t := time.Now()

	req := model.QueryUserLogRequest{}
	if err := ctx.BindQuery(&req); err != nil {
		req.OrderType = 0
	}

	newData := emodel.My_online_order{
		OrderNo:    orderNo,
		Uid:        operator.Id,
		Mobile:     operator.Mobile,
		CreateTime: &t,
		Skuids:     skuids,
	}
	if orderType == "2" {
		response.Error(ctx, sferrors.NewStringf("暂不支持"))
		return
		//查询我的上级
		puser, err := dto.GetSysUserDetailById(operator.Pid)
		if err != nil {
			response.Error(ctx, err)
			return
		}
		newData.Uid = puser.Id
		newData.Mobile = puser.Mobile
		newData.ChId = operator.Id
	}

	if err = db.GetDb().Create(&newData).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "Success")
}

// CreateChildOrderTow  添加订单
// @Summary		添加订单
// @Description	添加订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-child-order/{orderSn} [POST]
func (pro *ProductHandel) CreateChildOrderTow(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.Error(ctx, sferrors.NewString("活动调整"))
	return
	orderNo := strings.TrimSpace(ctx.Param("orderSn"))
	if orderNo == "" {
		response.Error(ctx, sferrors.NewStringf("用户id错误！"))
		return
	}

	var req model.AuthInfoReq
	if err = ctx.ShouldBind(&req); err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.ErrorBadRequest))
		return
	}
	var userinfo emodel.My_userinfo
	if err := db.GetDb().Where("uid=?", operator.Id).First(&userinfo).Error; err != nil {
		response.Error(ctx, sferrors.NewString("需要先绑定收款信息"))
		return
	}

	if req.Name == "" || req.DyUsername == "" {
		req.DyUsername = userinfo.ZfbUsername
		req.Name = operator.DyName
	} else {
		req.DyUsername = strings.TrimSpace(req.DyUsername)
	}

	if len(orderNo) < 8 {
		response.Error(ctx, sferrors.NewStringf("用户id错误!!!"))
		return
	}

	if operator.Level < 33 {
		response.Error(ctx, sferrors.NewStringf("自己级别最少33"))
		return
	}
	var cuser emodel.My_user
	db.GetDb().Select("pid", "level", "id", "mobile").
		Where("id=? and pid=? and create_time>'2025-06-14 23:59:59'", orderNo, operator.Id).First(&cuser)
	if cuser.Id <= 0 {
		response.Error(ctx, sferrors.NewStringf("该用户不是直推或者最新用户"))
		return
	}
	//
	if cuser.Level < 30 {
		response.Error(ctx, sferrors.NewStringf("直推需要满足30级"))
		return
	}

	//my-online-order
	var data emodel.My_child_order
	db.GetDb().Where("cid=? and status<2", orderNo).First(&data)

	if data.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("已经提交过了！"))
		return
	}

	if userinfo.ZfbUsername == "" {
		response.Error(ctx, sferrors.NewString("需要绑定支付宝"))
		return
	}

	t := time.Now()

	newData := emodel.My_child_order{
		Uid:         operator.Id,
		Mobile:      operator.Mobile,
		CreateTime:  &t,
		Cid:         cuser.Id,
		Cmobile:     cuser.Mobile,
		CLevel:      cuser.Level,
		DyName:      req.Name,
		ZfbUsername: req.DyUsername,
	}

	if err = db.GetDb().Create(&newData).Error; err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "Success")
}

// CreateOnlineOrderTowLevel  添加订单
// @Summary		添加订单
// @Description	添加订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/pro-online-order-level/{orderSn}/{orderType} [POST]
func (pro *ProductHandel) CreateOnlineOrderTowLevel(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	orderType := ctx.Param("orderType")
	if orderType == "" {
		response.Error(ctx, errors.New("非法操作"))
		return
	}
	level, err := strconv.Atoi(orderType)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	orderNo := strings.TrimSpace(ctx.Param("orderSn"))
	if orderNo == "" {
		response.Error(ctx, sferrors.NewStringf("单号错误！"))
		return
	}

	if len(orderNo) != 19 {
		response.Error(ctx, sferrors.NewStringf("单号错误!!!"))
		return
	}
	var oldOrder emodel.My_online_order
	db.GetDb().Where("order_no=?", orderNo).First(&oldOrder)
	if oldOrder.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("该订单已在电商订单内提交过！"))
		return
	}

	var dataW emodel.My_order_w
	db.GetDb().Where("order_no=? ", orderNo).First(&dataW)
	if dataW.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("该订单已被解锁使用！"))
		return
	}

	//my-online-order
	var data emodel.My_online_order_levels
	db.GetDb().Where("order_no=? ", orderNo).First(&data)
	if data.Status == 2 {
		response.Error(ctx, sferrors.NewStringf("该订单状态审核失败！"))
		return
	}
	if data.Id > 0 {
		response.Error(ctx, sferrors.NewStringf("该订单之前已经被使用了！"))
		return
	}

	skuids, respone, err := service.GetYongjinOrderDetail(orderNo)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if respone != true {
		response.Error(ctx, errors.New("请确定订单已经全部取消或退款"))
		return
	}

	t := time.Now()
	data.OrderNo = orderNo
	data.Mobile = operator.Mobile
	data.Uid = operator.Id
	data.CreateTime = &t
	data.Status = 0
	data.Skuids = skuids
	h := t.Hour()
	if h == 0 {
		h = 23
	} else {
		h = h - 1
	}
	data.Hours = h

	data.Level = level
	db.GetDb().Debug().Create(&data)

	key := fmt.Sprintf("new1%s_%d", orderType, operator.Id)
	err = cache.RedisContextSet(ctx, key, time.Now().AddDate(0, 0, 6), 144*time.Hour)

	response.OkData(ctx, "Success")
}

// CreateWOrderTow  添加订单
// @Summary		添加订单
// @Description	添加订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/w-online-order/{orderSn}/{orderType} [POST]
func (pro *ProductHandel) CreateWOrderTow(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}

	//
	//orderNo := strings.TrimSpace(ctx.Param("orderSn"))
	//if orderNo == "" {
	//	response.Error(ctx, sferrors.NewStringf("电商订单错误！"))
	//	return
	//}
	//
	//if len(orderNo) != 19 {
	//	response.Error(ctx, sferrors.NewStringf("电商订单错误!!!"))
	//	return
	//}
	//
	//var newOrder emodel.My_online_order_levels
	//db.GetDb().Where("order_no=?", orderNo).First(&newOrder)
	//if newOrder.Id > 0 {
	//	response.Error(ctx, sferrors.NewStringf("该订单已在阶梯订单中提交过"))
	//	return
	//}
	//
	//var data emodel.My_online_order
	//db.GetDb().Where("order_no=? and status<2", orderNo).First(&data)
	//if data.Id > 0 {
	//	response.Error(ctx, sferrors.NewStringf("在线单号已存在！"))
	//	return
	//}
	//
	//var dataW emodel.My_order_w
	//db.GetDb().Where("order_no=? ", orderNo).First(&dataW)
	//if dataW.Id > 0 {
	//	response.Error(ctx, sferrors.NewStringf("该订单已被解锁使用！"))
	//	return
	//}

	orderId := ctx.Param("orderId")
	if orderId == "" {
		response.Error(ctx, sferrors.NewStringf("非法操作！"))
		return
	}
	if orderId == "0" {
		orderId = "6"
	}

	type Heisuo struct {
		CreateTime time.Time `json:"create_time"`
		Days       int       `json:"days"`
		Id         int       `json:"id"`
		Num        float64   `json:"num"`
		Title      string    `json:"title"`
		Sy         int       `json:"sy"`
	}
	var jsData Heisuo
	if err = db.GetDb().Table("my_jiesuo").Where("id=?", orderId).First(&jsData).Error; err != nil {
		response.Error(ctx, err)
		return
	}
	if jsData.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("未找到数据"))
		return
	}
	if jsData.Sy <= 0 {
		response.Error(ctx, sferrors.NewStringf("当前名额已满"))
		return
	}

	//My_order_w
	var my_order_wCnt int64
	db.GetDb().Table("my_order_w").Where("uid=? and (status=0 or status=4)", operator.Id).Count(&my_order_wCnt)
	if my_order_wCnt > 0 {
		response.Error(ctx, sferrors.NewStringf("有进行中的订单"))
		return
	}
	//skuids, respone, err := service.GetYongjinOrderDetail(orderNo)
	//if err != nil {
	//	response.Error(ctx, err)
	//	return
	//}
	//if respone != true {
	//	response.Error(ctx, sferrors.NewStringf("请确定订单已经全部取消或退款"))
	//	return
	//}

	t := time.Now()

	money := jsData.Num
	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Select("id", "mobile", "w", "w_name", "w_account", "gold", "w_ppid", "w_pid").Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		if myUser.WName == "" || myUser.WAccount == "" {
			return sferrors.NewStringf("请先绑定文交所帐号")
		}

		if myUser.Gold < money {
			return sferrors.NewStringf("消费积分不足")
		}

		newData := emodel.My_order_w{
			//OrderNo:    orderNo,
			Uid:        operator.Id,
			Mobile:     operator.Mobile,
			CreateTime: &t,
			//Skuids:     skuids,
			Money:    money,
			WName:    myUser.WName,
			WAccount: myUser.WAccount,
			Status:   4,
			Days:     jsData.Days,
			WPid:     myUser.WPid,
			WPpid:    myUser.WPPid,
		}
		if err = tx.Omit("order_no").Create(&newData).Error; err != nil {
			return err
		}

		txErr = service.CreateGoldLog(tx, myUser, money, 2, myUser.Id, "消费积分解锁")
		if txErr != nil {
			return txErr
		}

		err := tx.Exec("update my_jiesuo set sy=sy-1 where id=? ", jsData.Id).Error
		if err != nil {
			return err
		}

		if myUser.W == 0 {
			err = tx.Table("my_user").Where("id=?", operator.Id).UpdateColumn("w", 1).Error
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "Success")
}

// CreateTzTiqu  添加订单
// @Summary		添加订单
// @Description	添加订单
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/tz-extract/{num} [POST]
func (pro *ProductHandel) CreateTzTiqu(ctx *gin.Context) {
	//response.Error(ctx, sferrors.NewStringf("暂未开放！"))
	//return

	//也要手续费的

	nowTime := time.Now().Format("1504")
	IntNow, err := strconv.Atoi(nowTime)

	zhuanStr := "提取时间为 10:00到15:00"
	if IntNow > 1000 && IntNow < 1500 {

	} else {
		response.Error(ctx, sferrors.NewStringf(zhuanStr))
		return
	}

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}

	num := ctx.Param("num")
	if num == "" {
		response.Error(ctx, sferrors.NewStringf("数量错误！"))
		return
	}

	numIntss, err := strconv.ParseFloat(num, 64)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if numIntss < 1 {
		response.Error(ctx, sferrors.NewStringf("最少1个"))
		return
	}

	var acount int64
	db.GetDb().Table("my_tz_extract").Debug().Where("uid=? and create_time>?", operator.Id, time.Now().Format("2006-01-02")+" 00:00:00").Count(&acount)
	if acount > 0 {
		response.Error(ctx, sferrors.NewStringf("一天只能提取一次"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}

		if myUser.WName == "" || myUser.WAccount == "" {
			return sferrors.NewStringf("请先绑定文交所帐号")
		}
		if myUser.WPid == 0 {
			return sferrors.NewStringf("需要先绑定上级才可以提取")
		}

		znun := float64(numIntss) * 1.1
		if myUser.Tz < znun {
			return sferrors.NewStringf("消费积分不足")
		}
		t := time.Now()
		newData := emodel.My_tz_extract{
			Uid:        operator.Id,
			Mobile:     operator.Mobile,
			CreateTime: &t,
			Money:      float64(numIntss),
			WName:      myUser.WName,
			WAccount:   myUser.WAccount,
			Sxf:        float64(numIntss) * 0.1,
		}
		if err = tx.Debug().Create(&newData).Error; err != nil {
			return err
		}

		txErr = service.CreateTzLog(tx, myUser, float64(numIntss), 3, myUser.Id, "通证提取")
		txErr = service.CreateTzLog(tx, myUser, float64(numIntss)*0.1, 3, myUser.Id, "通证提取手续费")
		if txErr != nil {
			return txErr
		}

		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "Success")
}
